const express = require('express')
const router = express.Router()
const db = require('../db')
const { authSchema } = require('../schema')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')

// 路由中间件 - 验证用户名和密码格式
router.use((req, res, next) => {
  const { error } = authSchema.validate(req.body)
  if (error) {
    return res.send({ code: 1, msg: error.details[0].message })
  }
  next()
})

// 注册路由
router.post('/register', async (req, res) => {
  const { username, password } = req.body
  try {
    // 判断用户名是否存在
    const [rows] = await db.execute('SELECT * FROM user WHERE username = ?', [
      username,
    ])
    if (rows.length > 0) {
      return res.send({ code: 1, msg: '用户名已存在' })
    }

    // 加密密码
    const hash = bcrypt.hashSync(password, 10)

    // 插入数据库
    await db.execute('INSERT INTO user (username, password) VALUES (?, ?)', [
      username,
      hash,
    ])
    res.send({ code: 0, msg: '注册成功' })
  } catch (error) {
    throw error
  }
})

// 登录路由
router.post('/login', async (req, res) => {
  const { username, password } = req.body
  try {
    // 判断用户名是否存在
    const [rows] = await db.execute('SELECT * FROM user WHERE username = ?', [
      username,
    ])
    if (rows.length === 0) {
      return res.send({ code: 1, msg: '用户名或密码错误' })
    }

    // 验证密码
    const isMatch = bcrypt.compareSync(password, rows[0].password)
    if (!isMatch) {
      return res.send({ code: 1, msg: '用户名或密码错误' })
    }

    // 生成token
    const payload = { id: rows[0].id }
    const secret = process.env.JWT_SECRET
    const expiresIn = process.env.JWT_EXPIRES_IN
    const token = 'Bearer ' + jwt.sign(payload, secret, { expiresIn })

    // 准备响应数据
    const data = {
      ...rows[0],
      password: undefined,
      token,
    }

    res.send({ code: 0, msg: '登录成功', data })
  } catch (error) {
    throw error
  }
})

module.exports = router
